package com.yuntoyun.codeavatar.app.activity.basic;

import android.Manifest;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.baidu.location.BDLocation;
import com.yuntoyun.codeavatar.app.R;
import com.yuntoyun.codeavatar.app.fwcore.activity.WebPageActivity;
import com.yuntoyun.codeavatar.app.fwcore.core.AppCoreSign;
import com.yuntoyun.codeavatar.app.fwcore.plug.map.baidu.PlugBaiduLocation;
import com.yuntoyun.fwcore.base.FwBaseActivity;
import com.yuntoyun.fwcore.model.FwResultJsonDataModel;
import com.yuntoyun.fwcore.model.FwResultJsonListDataModel;
import com.yuntoyun.fwcore.plug.network.retrofit.FwOkHttp;
import com.yuntoyun.fwcore.plug.tool.FwNavigationTool;
import com.yuntoyun.fwcore.tool.sms.SmsTool;
import com.yuntoyun.fwcore.tool.sms.SmsToolCallback;
import com.yuntoyun.fwcore.util.FwComponentUtil;
import com.yuntoyun.fwcore.util.FwIntentUtil;
import com.yuntoyun.fwcore.util.FwLogUtil;
import com.yuntoyun.fwcore.util.FwSoftInputUtil;
import com.yuntoyun.fwcore.util.FwToastUtil;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.functions.Consumer;

public class RegistActivity extends FwBaseActivity {

    private final String fTag = RegistActivity.class.getSimpleName();

    private final int gActionSms = 901;
    private final int gActionSubmit = 902;
    private final int gActionAgreement = 903;

    @BindView(R.id.ett_account)
    EditText ett_account;
    @BindView(R.id.ett_validcode)
    EditText ett_validcode;
    @BindView(R.id.ett_pwd)
    EditText ett_pwd;
    @BindView(R.id.tvw_getcode)
    TextView tvw_getcode;
    @BindView(R.id.ivw_agreement)
    ImageView ivw_agreement;

    //短信工具类
    private SmsTool gSmsTool = null;

    private String gAgreementUrl;

    //第三方工具
    private PlugBaiduLocation mLocation = null;
    private double longitude, latitude;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.obj instanceof BDLocation) {
                BDLocation bdLocation = (BDLocation) msg.obj;
                if (null != bdLocation) {
                    longitude = bdLocation.getLongitude();
                    latitude = bdLocation.getLatitude();
                    //节省资源
                    mLocation.stop();
                }
            }
        }
    };

    @Override
    protected void beforeLayout() {

    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_basic_regist;
    }

    @Override
    protected void initView() {
        //定位
        mLocation = new PlugBaiduLocation(fwActivity, mHandler);
        mLocation.init();
        this.doLocation();

        gSmsTool = new SmsTool(this, smsCallBack);
    }

    @Override
    protected void initData() {
        ivw_agreement.setTag(true);
    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected void initNavigation() {
        FwNavigationTool.setHeadBar(this, "注册");
    }

    @Override
    protected void messageHandler(Message msg) {

    }

    @Override
    protected void messageHandler(FwResultJsonDataModel model) {
        switch (model.getIndex()) {
            case gActionSms:
                int pCounter = fwGsonUtil.getInt(model.getFwData(), "expireTime");
                this.gSmsTool.setCounter(pCounter);
                this.gSmsTool.initTimer();
                this.gSmsTool.startTimer();
                break;
            case gActionSubmit:
                FwToastUtil.builder().makeText(model.getFwMessage());
                finish();
                break;
            case gActionAgreement:
                gAgreementUrl = fwGsonUtil.getString(model.getFwData(), "userAgreement");
                this.doAgreement();
                break;
        }
    }

    @Override
    protected void messageHandler(FwResultJsonListDataModel model) {

    }

    @OnClick({R.id.btn_submit, R.id.tvw_getcode, R.id.llt_agreement, R.id.tvw_agreement})
    @Override
    public void onClick(View v) {
        if (null == v) return;

        switch (v.getId()) {
            case R.id.btn_submit:
                this.doSubmit();
                break;
            case R.id.tvw_getcode:
                this.doSendSms();
                break;
            case R.id.llt_agreement:
                boolean isAgreed = FwComponentUtil.builder().getViewTag(ivw_agreement);
                ivw_agreement.setTag(!isAgreed);
                ivw_agreement.setImageResource((!isAgreed) ?
                        R.mipmap.icon_action_address_checked :
                        R.mipmap.icon_action_address_unchecked);
                break;
            case R.id.tvw_agreement:
                this.doAgreement();
                break;
            default:
                FwLogUtil.warn(this.fTag, "该组件ID不存在！");
                break;
        }
    }

    @Override
    protected void onDestroy() {
        this.gSmsTool.stopTimer();

        super.onDestroy();
    }

    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    private void doLocation() {
        //定位权限
        fwRxPermissionUtil.usePermission(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (aBoolean) {
                    mLocation.start();
                } else {
//                    FwAlertDialogUtil.builder().showCustomDialog(fwActivity, "警告"
//                            , "请开定位限，获取更佳体验!");
                }
            }
        }, Manifest.permission.ACCESS_FINE_LOCATION);
    }

    //协议
    private void doAgreement() {
        if (TextUtils.isEmpty(this.gAgreementUrl)) {
            HashMap<String, Object> map = new HashMap<>();
            AppCoreSign.addSign(map);
            Observable<FwResultJsonDataModel> observable = FwOkHttp.getFwAPIService().getAgreement(map);
            super.doPostData(this.gActionAgreement, observable, true);
        } else {
            Bundle extra = new Bundle();
            extra.putString("ext_title", "用户服务协议");
            extra.putString("ext_url", this.gAgreementUrl);
            FwIntentUtil.builder().startActivity(fwActivity, WebPageActivity.class, extra);
        }
    }

    private void doSubmit() {
        //关闭软键盘
        FwSoftInputUtil.builder().closeKeybord(this);

        String valAccount = FwComponentUtil.builder().getViewValue(ett_account);
        if (valAccount.length() != 11) {
            FwToastUtil.builder().makeText("请输入正确手机号");
            return;
        }

        String valCode = FwComponentUtil.builder().getViewValue(ett_validcode);
        if (valCode.length() != 6) {
            FwToastUtil.builder().makeText("请输入正确验证码");
            return;
        }

        String valPwd = FwComponentUtil.builder().getViewValue(ett_pwd);

        if (valPwd.length() < 1) {
            FwToastUtil.builder().makeText("请输入密码");
            return;
        }

        if (valPwd.length() < 6 || valPwd.length() > 20) {
            FwToastUtil.builder().makeText("请输入6~20位的密码");
            return;
        }

        HashMap<String, Object> map = new HashMap<>();
        if (Double.compare(this.longitude, 0f) == 1 && Double.compare(this.latitude, 0f) == 1) {
            map.put("fwUserLongitude", this.longitude + "");
            map.put("fwUserLatitude", this.latitude + "");
        }
        map.put("mobilephone", valAccount);
        map.put("validcode", valCode);
        map.put("userpwd", valPwd);
        AppCoreSign.addSign(map);
        Observable<FwResultJsonDataModel> observable =
                FwOkHttp.getFwAPIService().getRegist(map);
        super.doPostData(this.gActionSubmit, observable, true);
    }

    //发送验证码
    private void doSendSms() {
        String valAccount = FwComponentUtil.builder().getViewValue(ett_account);
        if (valAccount.length() != 11) {
            FwToastUtil.builder().makeText("请输入正确手机号");
            return;
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("mobilephone", valAccount);
        map.put("action", "regist");
        AppCoreSign.addSign(map);
        Observable<FwResultJsonDataModel> observable = FwOkHttp.getFwAPIService().getSmsSend(map);
        super.doPostData(this.gActionSms, observable, true);
    }

    //短信工具类回调事件
    private SmsToolCallback smsCallBack = new SmsToolCallback() {
        @Override
        public void initTimer() {
//            tvw_getcode.setEnabled(true);
//            tvw_getcode.setBackgroundResource(R.drawable.style_layout_button_main_bgcolor);
//            tvw_getcode.setText("发送验证码");
        }

        @Override
        public void startTimer(int counter) {
            tvw_getcode.setEnabled(false);
            tvw_getcode.setBackgroundResource(R.drawable.style_button_sms_disabled_bgcolor);
            tvw_getcode.setText(String.format("倒计时%d秒", counter));
        }

        @Override
        public void runTimer(int counter) {
            tvw_getcode.setText(String.format("倒计时%d秒", counter));
        }

        @Override
        public void stopTimer() {
            tvw_getcode.setBackgroundResource(R.drawable.style_button_sms_bgcolor);
            tvw_getcode.setText("发送验证码");
            tvw_getcode.setEnabled(true);
        }
    };
}
